package com.cv4j.app.fragment;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.app.Context;
import ohos.media.image.PixelMap;

import com.cv4j.app.ResourceTable;
import com.cv4j.app.utill.PixelMapUtil;
import com.cv4j.core.datamodel.CV4JImage;
import com.cv4j.core.datamodel.ImageProcessor;
import com.cv4j.core.hist.CalcHistogram;
import com.cv4j.core.hist.CompareHist;

/**
 * 直方图比较-两张相同的图界面
 *
 * @since 2021-05-18
 */
public class CompareHist2Fragment {
    private Context mContext;
    private Component component;
    private Image image0;
    private Image image1;
    private Text result;

    /**
     * CompareHist2Fragment
     *
     * @param context context
     */
    private CompareHist2Fragment(Context context) {
        mContext = context;
        init();
    }

    /**
     * getInstance
     *
     * @param context context
     * @return CompareHist2Fragment
     */
    public static CompareHist2Fragment getInstance(Context context) {
        CompareHist2Fragment compareHist2Fragment = new CompareHist2Fragment(context);
        return compareHist2Fragment;
    }

    private void init() {
        component = LayoutScatter.getInstance(mContext)
            .parse(ResourceTable.Layout_fragment_compare_hist_2, null, false);
        component.setLayoutConfig(new ComponentContainer.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT,
            ComponentContainer.LayoutConfig.MATCH_PARENT));
        image0 = (Image) component.findComponentById(ResourceTable.Id_image0);
        image1 = (Image) component.findComponentById(ResourceTable.Id_image1);
        result = (Text) component.findComponentById(ResourceTable.Id_result);
        initData();
    }

    private void initData() {
        PixelMap pixelMap = PixelMapUtil.getPixelMapFromResource(mContext, ResourceTable.Media_test_hist2).get();
        image0.setPixelMap(pixelMap);
        image1.setPixelMap(pixelMap);
        CV4JImage cv4jImage = new CV4JImage(pixelMap);
        ImageProcessor imageProcessor = cv4jImage.getProcessor();
        int[][] source;
        CalcHistogram calcHistogram = new CalcHistogram();
        int bins = 180;
        source = new int[imageProcessor.getChannels()][bins];
        calcHistogram.calcHSVHist(imageProcessor, bins, source, true);
        CompareHist compareHist = new CompareHist();
        StringBuilder sb = new StringBuilder();
        sb.append("巴氏距离:").append(compareHist.bhattacharyya(source[0], source[0])).append(System.lineSeparator())
            .append("协方差:").append(compareHist.covariance(source[0], source[0])).append(System.lineSeparator())
            .append("相关性因子:").append(compareHist.ncc(source[0], source[0]));
        result.setText(sb.toString());
    }

    public Component getComponent() {
        return component;
    }
}
